import datetime

from module_admin.dao.cms_device_dao import CmsDeviceDao
from module_admin.entity.do.cms_device import CmsDevice
from module_admin.dao.dept_dao import *
from module_admin.entity.vo.cms_device_vo import DeviceModel, DeviceForQuery
from module_admin.entity.vo.cms_device_vo import CrudDeviceResponse
from utils.uuid import UUID


class CmsDeviceService:

    @classmethod
    def create_device(cls, result_db: Session, page_object: DeviceModel):
        # 待审核
        page_object.state = 1
        uuid = UUID().uuid()
        page_object.id = int(uuid)
        page_object.device_id = "dev_" + uuid
        try:
            CmsDeviceDao.create_device(result_db, page_object)
            result_db.commit()
            result = dict(is_success=True, message='新增成功')
        except Exception as e:
            result_db.rollback()
            result = dict(is_success=False, message=str(e))

        return CrudDeviceResponse(**result)

    @classmethod
    def delete_device(cls, query_db: Session, id: int):
        CmsDeviceDao.delete_device_by_id(query_db, id)
        query_db.commit()

    @classmethod
    def update_device(cls, db, device_update: DeviceModel):
        device_update_dict = device_update.dict(exclude_unset=True)
        if "warranty_period_desc" in device_update_dict:
            del device_update_dict["warranty_period_desc"]
        try:
            CmsDeviceDao.update_device_by_id(db, device_update_dict)
            db.commit()
            result = dict(is_success=True, message='更新成功')
        except Exception as e:
            db.rollback()
            result = dict(is_success=False, message=str(e))
        return CrudDeviceResponse(**result)

    @classmethod
    def get_device(cls, query_db: Session, id: int):
        device_by_id: CmsDevice = CmsDeviceDao.get_device_by_id(query_db, id)
        return DeviceModel(**device_by_id.__dict__)

    @classmethod
    def list(cls, db: Session, query_object: DeviceForQuery):
        device_list_result = CmsDeviceDao.list(db, query_object)
        now = datetime.datetime.now()
        list0 = []
        for e in device_list_result:
            model = DeviceModel(**e.__dict__)
            if model.warranty_period is not None:
                model.warranty_period_desc = "过保" if model.warranty_period < now else "在保"
            list0.append(model)
        return list0
